﻿using System;
using System.Data;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using BrnMall.Core;
using PetaPoco;
using BrnMall.Manager.Manager.Product;

namespace BrnMall.Services
{
    /// <summary>
    /// 商品操作管理类
    /// </summary>
    public partial class Products
    {
        /// <summary>
        /// 获得商品
        /// </summary>
        /// <param name="pid">商品id</param>
        /// <returns></returns>
        public static ProductInfo GetProductById(int pid)
        {
            if (pid < 1) return null;
            return BrnMall.Data.Products.GetProductById(pid);
        }

        /// <summary>
        /// 获得部分商品
        /// </summary>
        /// <param name="pid">商品id</param>
        /// <returns></returns>
        public static PartProductInfo GetPartProductById(int pid)
        {
            if (pid < 1) return null;
            return BrnMall.Data.Products.GetPartProductById(pid);
        }

        /// <summary>
        /// 获得部分商品
        /// </summary>
        /// <param name="storeId">店铺id</param>
        /// <param name="psn">商品货号</param>
        /// <returns></returns>
        public static PartProductInfo GetPartProductByPSN(int storeId, string psn)
        {
            if (storeId < 1 || string.IsNullOrEmpty(psn)) return null;
            return BrnMall.Data.Products.GetPartProductByPSN(storeId, psn);
        }

        /// <summary>
        /// 获得部分商品列表
        /// </summary>
        /// <param name="pidList">商品id列表</param>
        /// <returns></returns>
        public static List<PartProductInfo> GetPartProductList(string pidList)
        {
            if (string.IsNullOrEmpty(pidList))
                return new List<PartProductInfo>();
            return BrnMall.Data.Products.GetPartProductList(pidList);
        }

        /// <summary>
        /// 获得商品的影子访问数量
        /// </summary>
        /// <param name="pid">商品id</param>
        /// <returns></returns>
        public static int GetProductShadowVisitCountById(int pid)
        {
            return BrnMall.Data.Products.GetProductShadowVisitCountById(pid);
        }

        /// <summary>
        /// 更新商品的影子访问数量
        /// </summary>
        /// <param name="pid">商品id</param>
        /// <param name="visitCount">访问数量</param>
        public static void UpdateProductShadowVisitCount(int pid, int visitCount)
        {
            BrnMall.Data.Products.UpdateProductShadowVisitCount(pid, visitCount);
        }

        /// <summary>
        /// 预约数量
        /// </summary>
        /// <param name="pid"></param>
        /// <returns></returns>
        public static int GetProductAppointCountById(int pid)
        {
            return BrnMall.Data.Products.GetProductAppointCountById(pid);
        }

        /// <summary>
        /// 预约数量
        /// </summary>
        /// <param name="pid"></param>
        /// <param name="appointCount"></param>
        public static void UpdateProductAppointCount(int pid, int appointCount)
        {
            BrnMall.Data.Products.UpdateProductAppointCount(pid, appointCount);
        }

        /// <summary>
        /// 增加商品的影子销售数量
        /// </summary>
        /// <param name="pid">商品id</param>
        /// <param name="saleCount">销售数量</param>
        public static void AddProductShadowSaleCount(int pid, int saleCount)
        {
            BrnMall.Data.Products.AddProductShadowSaleCount(pid, saleCount);
        }

        /// <summary>
        /// 增加商品的影子评价数量
        /// </summary>
        /// <param name="pid">商品id</param>
        /// <param name="starType">星星类型</param>
        public static void AddProductShadowReviewCount(int pid, int starType)
        {
            BrnMall.Data.Products.AddProductShadowReviewCount(pid, starType);
        }

        /// <summary>
        /// 获得分类商品列表
        /// </summary>
        /// <param name="pageSize">每页数</param>
        /// <param name="pageNumber">当前页数</param>
        /// <param name="cateId">分类id</param>
        /// <param name="brandId">品牌id</param>
        /// <param name="filterPrice">筛选价格</param>
        /// <param name="catePriceRangeList">分类价格范围列表</param>
        /// <param name="attrValueIdList">属性值id列表</param>
        /// <param name="onlyStock">是否只显示有货</param>
        /// <param name="sortColumn">排序列</param>
        /// <param name="sortDirection">排序方向</param>
        /// <returns></returns>
        public static List<StoreProductInfo> GetCategoryProductList(int pageSize, int pageNumber, int cateId, int brandId, int filterPrice, string[] catePriceRangeList, List<int> attrValueIdList, int onlyStock, int sortColumn, int sortDirection)
        {
            return BrnMall.Data.Products.GetCategoryProductList(pageSize, pageNumber, cateId, brandId, filterPrice, catePriceRangeList, attrValueIdList, onlyStock, sortColumn, sortDirection);
        }

        /// <summary>
        /// 获得分类商品数量
        /// </summary>
        /// <param name="cateId">分类id</param>
        /// <param name="brandId">品牌id</param>
        /// <param name="filterPrice">筛选价格</param>
        /// <param name="catePriceRangeList">分类价格范围列表</param>
        /// <param name="attrValueIdList">属性值id列表</param>
        /// <param name="onlyStock">是否只显示有货</param>
        /// <returns></returns>
        public static int GetCategoryProductCount(int cateId, int brandId, int filterPrice, string[] catePriceRangeList, List<int> attrValueIdList, int onlyStock)
        {
            return BrnMall.Data.Products.GetCategoryProductCount(cateId, brandId, filterPrice, catePriceRangeList, attrValueIdList, onlyStock);
        }

        /// <summary>
        /// 获得店铺分类商品列表
        /// </summary>
        /// <param name="pageSize">每页数</param>
        /// <param name="pageNumber">当前页数</param>
        /// <param name="storeCid">店铺分类id</param>
        /// <param name="startPrice">开始价格</param>
        /// <param name="endPrice">结束价格</param>
        /// <param name="sortColumn">排序列</param>
        /// <param name="sortDirection">排序方向</param>
        /// <returns></returns>
        public static List<PartProductInfo> GetStoreClassProductList(int pageSize, int pageNumber, int storeCid, int startPrice, int endPrice, int sortColumn, int sortDirection)
        {
            return BrnMall.Data.Products.GetStoreClassProductList(pageSize, pageNumber, storeCid, startPrice, endPrice, sortColumn, sortDirection);
        }

        /// <summary>
        /// 获得店铺分类商品列表
        /// </summary>
        /// <param name="pageSize">每页数</param>
        /// <param name="pageNumber">当前页数</param>
        /// <param name="storeCid">店铺分类id</param>
        /// <param name="storeId"></param>
        /// <param name="startPrice">开始价格</param>
        /// <param name="endPrice">结束价格</param>
        /// <param name="sortColumn">排序列</param>
        /// <param name="sortDirection">排序方向</param>
        /// <param name="saleMode">展示模型0:不区分，1：线下扫码2：线上交易</param>
        /// <returns></returns>
        public static List<PartProductInfo> GetStoreClassProductList(int pageSize, int pageNumber, int storeCid, int storeId, int startPrice, int endPrice, int sortColumn, int sortDirection, int saleMode = 0)
        {
            return BrnMall.Data.Products.GetStoreClassProductList(pageSize, pageNumber, storeCid, storeId, startPrice, endPrice, sortColumn, sortDirection, saleMode);
        }

        /// <summary>
        /// 获得店铺分类商品数量
        /// </summary>
        /// <param name="storeCid">店铺分类id</param>
        /// <param name="startPrice">开始价格</param>
        /// <param name="endPrice">结束价格</param>
        /// <returns></returns>
        public static int GetStoreClassProductCount(int storeCid, int startPrice, int endPrice)
        {
            return BrnMall.Data.Products.GetStoreClassProductCount(storeCid, startPrice, endPrice);
        }

        /// <summary>
        /// 获得店铺分类商品数量
        /// </summary>
        /// <param name="storeCid">店铺分类id</param>
        /// <param name="startPrice">开始价格</param>
        /// <param name="endPrice">结束价格</param>
        /// <param name="storeId"></param>
        /// <param name="saleMode">展示模型0:不区分，1：线下扫码2：线上交易</param>
        /// <returns></returns>
        public static int GetStoreClassProductCount(int storeCid, int startPrice, int endPrice, int storeId, int saleMode = 0)
        {
            return BrnMall.Data.Products.GetStoreClassProductCount(storeCid, startPrice, endPrice, storeId, saleMode);
        }

        /// <summary>
        /// 获得店铺特征商品列表
        /// </summary>
        /// <param name="count">数量</param>
        /// <param name="storeId">店铺id</param>
        /// <param name="storeCid">店铺分类id</param>
        /// <param name="trait">特征(0代表精品,1代表热销,2代表新品)</param>
        /// <param name="saleMode">展示模型0:不区分，1：线下扫码,2：线上交易</param>
        /// <returns></returns>
        public static List<PartProductInfo> GetStoreTraitProductList(int count, int storeId, int storeCid, int trait, int saleMode = 0)
        {
            var storeTraitProductList = BrnMall.Data.Products.GetStoreTraitProductList(count, storeId, storeCid, trait, saleMode);
            Trace.TraceInformation($"count{count} storeId{storeId} storeCid{storeCid} trait{trait} saleMode{saleMode} recount{storeTraitProductList.Count}");

            return storeTraitProductList;
        }

        /// <summary>
        /// 获得店铺销量商品列表
        /// </summary>
        /// <param name="count">数量</param>
        /// <param name="storeId">店铺id</param>
        /// <param name="storeCid">店铺分类id</param>
        /// <returns></returns>
        public static List<PartProductInfo> GetStoreSaleProductList(int count, int storeId, int storeCid)
        {
            var storeSaleProductList = BrnMall.Data.Products.GetStoreSaleProductList(count, storeId, storeCid);

            return storeSaleProductList;
        }

        /// <summary>
        /// 获得商品汇总列表
        /// </summary>
        /// <param name="pidList">商品id列表</param>
        /// <returns></returns>
        public static DataTable GetProductSummaryList(string pidList)
        {
            return BrnMall.Data.Products.GetProductSummaryList(pidList);
        }

        /// <summary>
        /// 获得商品属性
        /// </summary>
        /// <param name="pid">商品id</param>
        /// <param name="attrId">属性id</param>
        /// <returns></returns>
        public static ProductAttributeInfo GetProductAttributeByPidAndAttrId(int pid, int attrId)
        {
            return BrnMall.Data.Products.GetProductAttributeByPidAndAttrId(pid, attrId);
        }

        /// <summary>
        /// 获得商品属性列表
        /// </summary>
        /// <param name="pid">商品id</param>
        /// <returns></returns>
        public static List<ProductAttributeInfo> GetProductAttributeList(int pid)
        {
            return BrnMall.Data.Products.GetProductAttributeList(pid);
        }

        /// <summary>
        /// 获得扩展商品属性列表
        /// </summary>
        /// <param name="pid">商品id</param>
        /// <returns></returns>
        public static List<ExtProductAttributeInfo> GetExtProductAttributeList(int pid)
        {
            return BrnMall.Data.Products.GetExtProductAttributeList(pid);
        }

        /// <summary>
        /// 获得商品的sku项列表
        /// </summary>
        /// <param name="pid">商品id</param>
        /// <returns></returns>
        public static DataTable GetProductSKUItemList(int pid)
        {
            return BrnMall.Data.Products.GetProductSKUItemList(pid);
        }

        /// <summary>
        /// 获取sku产品的总销量
        /// </summary>
        /// <param name="attrid"></param>
        /// <param name="skugid"></param>
        /// <returns></returns>
        public static int GetProductSkuAllsalecount(int attrid, int skugid)
        {
            return BrnMall.Data.Products.GetProductSkuAllsalecount(attrid, skugid);
        }

        /// <summary>
        /// 获得商品的sku项列表,
        /// </summary>
        /// <param name="pid">商品id</param>
        /// <returns></returns>
        public static List<ExtProductSKUItemInfo> GetProductSkuItemInfoList(int pid)
        {
            var dt = BrnMall.Data.Products.GetProductSKUItemList(pid);
            var r = new List<ExtProductSKUItemInfo>();
            if (dt == null || dt.Rows.Count == 0) return r;
            foreach (DataRow row in dt.Rows)
            {
                var t = new ExtProductSKUItemInfo();
                t.Pid = Convert.ToInt32(row["pid"]);
                t.AttrName = Convert.ToString(row["attrname"]).Trim();
                t.AttrShowType = Convert.ToInt32(row["attrshowtype"]);
                t.AttrValue = Convert.ToString(row["attrvalue"]).Trim();
                t.IsInput = Convert.ToInt32(row["isinput"]);
                t.AttrId = Convert.ToInt32(row["attrid"]);

                t.RecordId = Convert.ToInt32(row["recordid"]);
                t.SKUGid = Convert.ToInt32(row["skugid"]);
                t.AttrValueId = Convert.ToInt32(row["attrvalueid"]);
                t.InputValue = Convert.ToString(row["inputvalue"]).Trim();

                r.Add(t);
            }
            return r;
        }

        /// <summary>
        /// 获得商品的sku列表
        /// </summary>
        /// <param name="skuGid">sku组id</param>
        /// <returns></returns>
        public static List<ExtProductSKUItemInfo> GetProductSKUListBySKUGid(int skuGid)
        {
            if (skuGid > 0)
                return BrnMall.Data.Products.GetProductSKUListBySKUGid(skuGid);
            return new List<ExtProductSKUItemInfo>();
        }

        /// <summary>
        /// 获得商品有效的的sku列表，不包含以下规则的商品SKU
        /// 已下线，不在显示时间
        /// </summary>
        /// <param name="skuGid">sku组id</param>
        /// <returns></returns>
        public static List<ExtProductSKUItemInfo> GetProductExitingSkuListBySkuGid(int skuGid)
        {
            if (skuGid > 0)
                return BrnMall.Data.Products.GetProductSKUListBySKUGid(skuGid).Where(t => IsExitingSku(t.Pid)).ToList();
            return new List<ExtProductSKUItemInfo>();
            //if (skuGid > 0)
            //{
            //    var result= BrnMall.Data.Products.GetProductSKUListBySKUGid(skuGid);
            //    var pids = result.Select(t => t.Pid).Distinct().Where(IsExitingSku).ToList();
            //    return result.Where(t => pids.Contains(t.Pid)).ToList();
            //}

            //return new List<ExtProductSKUItemInfo>();
        }

        /// <summary>
        /// 判断该条SKU产品是否有效
        /// </summary>
        /// <param name="pid"></param>
        /// <returns></returns>
        private static bool IsExitingSku(int pid)
        {
            var partProductInfo = Products.GetPartProductById(pid);
            if (partProductInfo == null) return false;
            return partProductInfo.State == 0 && partProductInfo.SalehourStart <= DateTime.Now.Hour && partProductInfo.SaleHourEnd >= DateTime.Now.Hour;
        }

        /// <summary>
        /// 获得商品图片列表
        /// </summary>
        /// <param name="pid">商品id</param>
        /// <returns></returns>
        public static List<ProductImageInfo> GetProductImageList(int pid)
        {
            if (pid > 0)
                return BrnMall.Data.Products.GetProductImageList(pid);

            return new List<ProductImageInfo>();
        }

        public static List<ProductImageInfo> GetProductAllImageList(int pid)
        {
            if (pid > 0)
                return BrnMall.Data.Products.GetProductAllImageList(pid);

            return new List<ProductImageInfo>();
        }

        /// <summary>
        /// 获得商品库存
        /// </summary>
        /// <param name="pid">商品id</param>
        /// <returns></returns>
        public static ProductStockInfo GetProductStockByPid(int pid)
        {
            return BrnMall.Data.Products.GetProductStockByPid(pid);
        }

        /// <summary>
        /// 获得商品库存数量
        /// </summary>
        /// <param name="pid">商品id</param>
        /// <returns></returns>
        public static int GetProductStockNumberByPid(int pid)
        {
            return BrnMall.Data.Products.GetProductStockNumberByPid(pid);
        }

        /// <summary>
        /// 增加商品库存数量
        /// </summary>
        /// <param name="orderProductList">订单商品列表</param>
        public static void IncreaseProductStockNumber(List<OrderProductInfo> orderProductList)
        {
            BrnMall.Data.Products.IncreaseProductStockNumber(orderProductList);
        }

        /// <summary>
        /// 减少商品库存数量
        /// </summary>
        /// <param name="orderProductList">订单商品列表</param>
        public static void DecreaseProductStockNumber(List<OrderProductInfo> orderProductList)
        {
            orderProductList.RemoveAll(p => p.BookNumber > 0 && p.BookStartTime.Date != DateTime.Now.Date);//不是当天的预约，不见库存
            if (orderProductList.Count > 0)
                BrnMall.Data.Products.DecreaseProductStockNumber(orderProductList);
        }

        /// <summary>
        /// 增加商品库存数量
        /// </summary>
        /// <param name="orderProductList">订单商品列表</param>
        public static void IncreaseProductStockNumberForBook(List<OrderProductInfo> orderProductList)
        {
            BrnMall.Data.Products.IncreaseProductStockNumberForBook(orderProductList);
        }

        /// <summary>
        /// 减少商品库存数量
        /// </summary>
        /// <param name="orderProductList">订单商品列表</param>
        public static void DecreaseProductStockNumberForBook(List<OrderProductInfo> orderProductList)
        {
            BrnMall.Data.Products.DecreaseProductStockNumberForBook(orderProductList);
        }

        /// <summary>
        /// 获得商品库存列表
        /// </summary>
        /// <param name="pidList">商品id列表</param>
        /// <returns></returns>
        public static List<ProductStockInfo> GetProductStockList(string pidList)
        {
            if (!string.IsNullOrEmpty(pidList))
                return BrnMall.Data.Products.GetProductStockList(pidList);

            return new List<ProductStockInfo>();
        }

        /// <summary>
        /// 获得商品库存
        /// </summary>
        /// <param name="pid">商品id</param>
        /// <param name="productStockList">商品库存列表</param>
        /// <returns></returns>
        public static ProductStockInfo GetProductStock(int pid, List<ProductStockInfo> productStockList)
        {
            foreach (ProductStockInfo productStockInfo in productStockList)
            {
                if (productStockInfo.Pid == pid)
                    return productStockInfo;
            }
            return null;
        }

        /// <summary>
        /// 获得关联商品列表
        /// </summary>
        /// <param name="pid">商品id</param>
        /// <returns></returns>
        public static List<PartProductInfo> GetRelateProductList(int pid)
        {
            return BrnMall.Data.Products.GetRelateProductList(pid);
        }

        #region 小程序 2017-06-08

        /// <summary>
        /// 获取店铺首页的商品
        /// </summary>
        /// <param name="storeId">店铺ID</param>
        /// <param name="cateId">商品分类ID</param>
        /// <returns></returns>
        public static List<PartProductInfo> GetWXProductTop(int storeId, int cateId, int topRow)
        {
            return Data.Products.GetWXProductTop(storeId, cateId, topRow);
        }

        #endregion 小程序 2017-06-08

        #region 酒店价格

        /// <summary>
        /// 获取商品的日期价
        /// </summary>
        /// <param name="pid"></param>
        /// <param name="day"></param>
        /// <param name="未设置时显示的价格"></param>
        /// <returns></returns>
        public static decimal GetDayPrice(int pid, DateTime day, decimal defaultShopPrice)
        {
            decimal shopPrice = defaultShopPrice;
            var listPrice = ProductPriceManager.GetListByDate(pid, day.ToString("yyyyMMdd"), day.AddDays(1).ToString("yyyyMMdd"));
            if (listPrice != null)
            {
                foreach (var item in listPrice)
                {
                    if (item.AppointDay.Equals(day.ToString("yyyyMMdd")))  //根据日期匹配价格
                        shopPrice = item.Price;
                }
            }
            return shopPrice;
        }

        /// <summary>
        /// 获取时间段的价格
        /// </summary>
        /// <param name="pid"></param>
        /// <param name="startTime">开始日期(含当天)</param>
        /// <param name="endTime">截止日期(不含当天)</param>
        /// <param name="defaultShopPrice"></param>
        /// <returns></returns>
        public static decimal GetTotalPrice(int pid, DateTime startTime, DateTime endTime)
        {
            decimal total = 0;
            var listPrice = ProductPriceManager.GetListByDate(pid, startTime.ToString("yyyyMMdd"), endTime.AddDays(1).ToString("yyyyMMdd"));
            var defaultShopPrice = Products.GetProductById(pid).ShopPrice;

            var days = (int)endTime.Subtract(startTime).TotalDays;  //总天数
            for (var i = 0; i < days; i++)
            {
                decimal shopPrice = defaultShopPrice;
                var day = startTime.AddDays(i).ToString("yyyyMMdd");
                if (listPrice != null)
                {
                    foreach (var item in listPrice)
                    {
                        if (item.AppointDay.Equals(day))  //根据日期匹配价格
                            shopPrice = item.Price;
                    }

                    //单品促销活动
                    var single = Promotions.GetSinglePromotionByPidAndTime(pid, startTime.AddDays(i));
                    if (single != null)
                    {
                        switch (single.DiscountType)
                        {
                            case 0: shopPrice = shopPrice * Convert.ToDecimal(single.DiscountValue) * 0.1m; break; //打折时, 8表示8折
                            case 1: shopPrice = shopPrice - Convert.ToDecimal(single.DiscountValue); break;
                            case 2: shopPrice = shopPrice = Convert.ToDecimal(single.DiscountValue); break;
                        }
                    }
                    shopPrice = shopPrice < 0 ? 0 : shopPrice;
                }
                total += shopPrice;
            }
            return total;
        }

        #endregion 酒店价格
    }
}